import { PlanGetPage, GetTeamAchievement, GetAllPlan } from "@/api/teacher/plan";
import { reactive, ref, onMounted } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { ClassGetAll } from "@/api/teacher/zsclass";
import { ExportTeam } from "@/api/teacher/result";
import { GetAllDelegateTeamByClassId } from "@/api/teacher/delegateTeam";
// import { ElMessage, FormInstance } from "element-plus";
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";
import qs from "qs";
import { ElMessage } from "element-plus";
export function useOrganization() {
  const formRef = ref();
  const loading = ref(false);
  const SelectItemList = ref<any>([]);
  const planList = ref<any>([]);
  const classList = ref<any>([]);
  const teamList = ref<any>([]);
  const dataList = ref<any>([]);
  const result = reactive({
    classId: "",
    planId: "",
    teamId: ""
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "团队姓名",
      prop: "teamName",
      minWidth: 100
    },
    {
      label: "总分",
      minWidth: 180,
      prop: "totalScore"
    }
  ];

  const rules = {
    planId: [
      { required: true, message: '请选择计划名称', trigger: 'blur' },
    ],
    classId: [
      { required: true, message: '请选择计划名称', trigger: 'blur' },
    ],
    teamId: [
      { required: true, message: '请选择计划名称', trigger: 'blur' },
    ],
  }

  // 获取计划名称、班级下拉数据
  async function GetAllPlans() {
    //获取班级下拉框
    const response = await ClassGetAll();
    if (response.success == true) {
      classList.value = response.data;
    }
    //获取计划下拉框
    const { data, success } = await GetAllPlan();
    if (success) {
      planList.value = data;
    }
  }

  // 通过班级获取团队
  async function handchangeteam(event) {
    result.teamId = "";
    const res = await GetAllDelegateTeamByClassId(event);
    if (res.success) {
      teamList.value = res.data
    } else {
      ElMessage.error()
    }
  }

  function handleCurrentChange(val: number) {
    onSearch(formRef.value);
  }
  function handleSizeChange(val: number) {
    onSearch(formRef.value);
  }


  // 导出xlsx 文档
  async function deriveXlsx(row) {
    (row as any).validate(async valid => {
      if (!valid) return;
      const data = qs.stringify({
        ...result,
      })
      let res = await ExportTeam(data)
      if (res.success) {
        //把导出的表头转成中文
        const chineseHeaders = {
          teamName: "团队名称",
          totalScore: "总分",
        }

        const chineseData = res.data.map(item => {
          const newItem = {};
          for (const key in item) {
            if (key in chineseHeaders) {
              newItem[chineseHeaders[key]] = item[key];
            }
          }
          return newItem;
        });
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.json_to_sheet(chineseData);
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
        const wbout = XLSX.write(wb, { bookType: "xlsx", type: "array" });
        try {
          FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            "团队成绩数据.xlsx"
          );
          ElMessage.success('文件下载完成');
        } catch (error) {
          ElMessage.error('文件下载失败');
          console.error(error, wbout);
          // }
        }
      } else {
        ElMessage.error(res.msg)
      }
    })


    // const wd = XLSX.utils.table_to_book(document.querySelector("#XLSX_table"));
    // const wbout = XLSX.write(wd, {
    //   bookType: "xlsx",
    //   bookSST: true,
    //   type: "array"
    // });
    // try {
    //   FileSaver.saveAs(
    //     new Blob([wbout], { type: "application/octet-stream" }),
    //     "idea.xlsx"
    //   );
    // } catch (error) {
    //   if (typeof console !== "undefined") console.error(error, wbout);
    // }
    // return wbout;
  }

  async function onSearch(row) {
    (row as any).validate(async valid => {
      if (!valid) return;
      loading.value = true;
      const data = {
        ...result,
        pageindex: pagination.currentPage,
        pagesize: pagination.pageSize
      }
      const req = await GetTeamAchievement(data);
      if (req.success) {
        loading.value = false;
        dataList.value = req?.data?.items;
        pagination.total = req?.data?.totalCount;
      } else {
        dataList.value = []
        ElMessage.error(req.msg)
        setTimeout(() => {
          loading.value = false;
        }, 1500)
      }
    })
  }

  onMounted(() => {
    GetAllPlans();
  });

  return {
    rules,
    result,
    columns,
    dataList,
    loading,
    formRef,
    teamList,
    deriveXlsx,
    pagination,
    planList,
    classList,
    SelectItemList,
    handchangeteam,
    handleSizeChange,
    handleCurrentChange,
    onSearch
  };
}
